﻿using System;
using System.Text;
using MyFramework.Domain.Model;
using Newtonsoft.Json;
using RabbitMQ.Client;

namespace MQProducer
{
    class Program
    {
        static void Main(string[] args)
        {
           
               while (true)
               {
                   var c = Console.ReadLine();
                   try
                   {
                       Producer(c);
                    }
                   catch (Exception e)
                   {
                       Console.WriteLine(e);
                    
                   }
                   
               }
        }
        public static void Producer(string value)
        {
            try
            {
                var qName = "logging";
                var exchangeName = "logexchange";
                var exchangeType = "fanout";//topic、fanout
                var routingKey = "*";
                var uri = new Uri("amqp://192.168.123.49:5672/");
                var factory = new ConnectionFactory
                {
                    UserName = "terrydash",
                    Password = "xgxxgx",
                    RequestedHeartbeat = 0,
                    Endpoint = new AmqpTcpEndpoint(uri)
                };
                using (var connection = factory.CreateConnection())
                {
                    using (var channel = connection.CreateModel())
                    {
                        //设置交换器的类型
                        channel.ExchangeDeclare(exchangeName, exchangeType);
                        //声明一个队列，设置队列是否持久化，排他性，与自动删除
                        channel.QueueDeclare(qName, true, false, false, null);
                        //绑定消息队列，交换器，routingkey
                        channel.QueueBind(qName, exchangeName, routingKey);
                        var properties = channel.CreateBasicProperties();
                        //队列持久化
                        properties.Persistent = true;
                        properties.DeliveryMode = 2;
                        var log = new Log
                        {
                            DateTime = DateTime.Now,
                            LogLevel = LogLevel.DEBUG,
                            ProgramInfo = new ProgramInfo
                            {
                                Guid = Guid.NewGuid(),
                                Manager = "xgx",
                                Name = typeof(Program).ToString(),
                                Type = ProgramType.WebAPP
                            },
                            LogInfo = value
                        };
                        var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(log));
                        //发送信息
                        channel.BasicPublish(exchangeName, routingKey, properties, body);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
